import xtpzService from '@/api/xtpz'
import { getRygnpzInputDTO } from '@/api/xtpz-dto'
import wjfwSerivce from '@/api/wjfw'
import { ElMessage } from 'element-plus'
interface saveRygnpzParams {
  dwbm: string
  gnbm: string
  rybm: string
  json: any
  name: string
}

// 保存配置
const saveRygnpz = async (obj: saveRygnpzParams) => {
  // 上传文件
  const file = stringToFile(JSON.stringify(obj.json), obj.name)
  const wjxh = await singleUploadFile(file)
  const params = {
    dwbm: obj.dwbm,
    gnbm: obj.gnbm,
    rybm: obj.rybm,
    wjxh: wjxh,
  }
  const res = await xtpzService.saveRygnpz(params).catch((err) => {
    !err.isError && ElMessage({ type: 'warning', message: err.message })
    return false
  })

  return res
}

//获取配置

const getRygnpz = async (obj: getRygnpzInputDTO) => {
  const res = await xtpzService.getRygnpz(obj).catch((err) => {
    !err.isError && ElMessage({ type: 'warning', message: err.message })
    return {
      data: { wjxh: '' },
    }
  })
  if (!res.data?.wjxh) {
    return
  }
  // 下载文件
  const wjRes = await wjfwSerivce.download({ wjbh: res.data.wjxh })
  if (wjRes.code === -1) {
    return null
  } else {
    return wjRes
  }
}

//string转file
const stringToFile = (str: string, filename: string) => {
  const blob = new Blob([str])
  return new File([blob], filename)
}

/**
 * 上传文件
 */
const singleUploadFile = async (file: any) => {
  const formData = new FormData()
  formData.append('file', file)
  const res = await wjfwSerivce.upload(formData).catch((err) => {
    !err.isError && ElMessage({ type: 'warning', message: err.message })
    return {
      data: {
        wjbh: '',
      },
    }
  })
  return res?.wjbh || ''
}

export { saveRygnpz, getRygnpz }
